<template>
  <el-dialog v-model="dialogVisible" title="编辑信息" :fullscreen="isMobile">
    <el-form ref="form" :model="formData" :rules="rules" label-width="auto">
      <el-form-item label="头像" prop="avatar">
        <el-avatar :size="80" :src="avatarPreview" shape="square" />
        <el-upload
          ref="uploadRef"
          :action=UPLAOD_ACTION_URL
          :headers="{ authorization: getToken() }"
          name="file"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarChange"
          :on-success="onUploadSuccess"
          accept="image/jpeg,image/png,image/gif"
        >
          <template #trigger>
            <el-button size="small" class="choose">选择头像</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="formData.username"
          :clearable="true"
          placeholder="请输入新的用户名"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { useStore } from "../stores";
import { updateUserApi } from "../api";
import { useWindowSize } from "@vueuse/core";
const UPLAOD_ACTION_URL = import.meta.env.VITE_BASE_URL + "api/user/avatar/";
const { width } = useWindowSize();
const isMobile = computed(() => width.value < 768);
const store = useStore();
const getToken = () => localStorage.getItem("token");
const dialogVisible = ref(false);
const avatarPreview = ref("");

const formData = ref({
  username: "",
  file: null,
});

const form = ref(null);
const uploadRef = ref(null);

const rules = reactive({
  username: [
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
});

const handleAvatarChange = (uploadFile) => {
  // 检查文件类型
  const isImage = ["image/jpeg", "image/png", "image/gif"].includes(
    uploadFile.raw.type
  );
  if (!isImage) {
    ElMessage.warning("只能上传 JPG/PNG/GIF 格式的图片!");
    return false;
  }

  // 检查文件大小 (10MB)
  const isLt10M = uploadFile.raw.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.warning("图片大小不能超过 10MB!");
    return false;
  }

  // 创建本地预览URL
  avatarPreview.value = URL.createObjectURL(uploadFile.raw);
  formData.value.file = uploadFile;
};

const onSubmit = async () => {
  if (formData.value.file) {
    uploadRef.value.submit();
  }
  if (
    formData.value.username.trim() &&
    formData.value.username !== store.userInfo.username
  ) {
    try {
      const res = await updateUserApi({ username: formData.value.username });
      ElMessage.success(res.message);
      localStorage.setItem("token", res.token);
      store.userInfo = res.user;
    } catch (error) {
      console.error("更新用户信息失败:", error);
    }
  }
  close();
};

const onUploadSuccess = (res) => {
  store.userInfo.avatar = `${import.meta.env.VITE_BASE_URL}api/user/avatar/${store?.userInfo?.id}?timestamp=${Date.now()}`;
  ElMessage.success(res.message);
};

const open = () => {
  dialogVisible.value = true;
  formData.value.username = store?.userInfo?.username;
  avatarPreview.value = store.userInfo.avatar;
};

const close = () => {
  dialogVisible.value = false;
  if (avatarPreview.value) {
    URL.revokeObjectURL(avatarPreview.value);
  }
  form.value.resetFields();
};

defineExpose({
  open,
  close,
});
</script>

<style scoped>
.choose {
  margin: 10px;
}
</style>
